/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package GUI;

import DBHandling.CategoryHandling;
import DBHandling.ItemHandling;
import Entity.Category;
import Entity.Item;
import Utilities.MyLibrary;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.RowFilter;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

/**
 *
 * @author HuyPV
 */
public class ItemSuppervisorPanel extends javax.swing.JPanel {

    private Vector<Item> items;
    private DefaultTableModel model;
    private Item item;
    private Vector<Category> categories;
    private ItemHandling ih;
    private TableRowSorter<TableModel> sorter;
    private String loginUser;

    /** Creates new form PanelIndex */
    public ItemSuppervisorPanel(String user) {
        initComponents();
        items = new Vector<Item>();
        setOptionTable();
        loadData();
    }

    public void setOptionTable() {
        model = new DefaultTableModel() {

            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        itemTable.setModel(model);

        model.addColumn("Item ID");
        model.addColumn("Item Name");
        model.addColumn("Category");
        model.addColumn("Unit");
        model.addColumn("Status");
        model.addColumn("Price");
        model.addColumn("Returnable");

        sorter = new TableRowSorter<TableModel>(model);
        itemTable.setRowSorter(sorter);

        //set option text Search
        txtSearch.getDocument().addDocumentListener(new DocumentListener() {

            @Override
            public void changedUpdate(DocumentEvent e) {
                if (cboSearchBy.getSelectedIndex() == 0) {
                    newFilter(txtSearch.getText(), 1);
                } else {
                    newFilter(txtSearch.getText(), 2);
                }
            }

            @Override
            public void insertUpdate(DocumentEvent e) {
                if (cboSearchBy.getSelectedIndex() == 0) {
                    newFilter(txtSearch.getText(), 1);
                } else {
                    newFilter(txtSearch.getText(), 2);
                }
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                if (cboSearchBy.getSelectedIndex() == 0) {
                    newFilter(txtSearch.getText(), 1);
                } else {
                    newFilter(txtSearch.getText(), 2);
                }
            }
        });
    }

    //load data from database to table 
    public void loadData() {
        try {
            //load add category on combobox
            CategoryHandling ch = new CategoryHandling();
            categories = new Vector<Category>();
            categories = ch.getCategories();

            cboCategories.removeAllItems();
            for (Category c : categories) {
                cboCategories.addItem(c.getCateName());
            }

            //load item
            MyLibrary.clearAllRow(model);      //clear all row on table
            ih = new ItemHandling();
            items = ih.getItems();
            for (Item i : items) {
                Vector v = new Vector();
                v.addElement(i.getItemID());
                v.addElement(i.getItemName());
                for (Category c : categories) {
                    if (c.getCateID().equals(i.getCateID())) {
                        v.addElement(c.getCateName());
                        break;
                    }
                }
                v.addElement(i.getUnit());
                v.addElement(i.getStatus());
                v.addElement(i.getPrice());
                v.addElement(i.isReturnable() ? "Yes" : "No");
                model.addRow(v);
            }


        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Error: " + ex.getMessage(), "Notice", JOptionPane.OK_OPTION);
        }

    }

    public void setData(Item item) {
        txtItemID.setText(item.getItemID());
        txtName.setText(item.getItemName());
        txtPrice.setText(String.valueOf(item.getPrice()));
        txtStatus.setText(String.valueOf(item.getStatus()));
        chkReturnable.setSelected(item.isReturnable());
        txtUnit.setText(item.getUnit());
        for (Category c : categories) {
            if (c.getCateID().equals(item.getCateID())) {
                cboCategories.setSelectedItem(c.getCateName());
                break;
            }
        }
    }

    public boolean isValidationForm() {
        String id = txtItemID.getText();
        String name = txtName.getText();
        String unit = txtUnit.getText();
        String price = txtPrice.getText();
        String status = txtStatus.getText();

        if (id.isEmpty()) {
            txtItemID.requestFocus();
            txtItemID.selectAll();
            JOptionPane.showMessageDialog(this, "The item id is not empty!", "Notice", JOptionPane.OK_OPTION);
            return false;
        } else if (name.isEmpty()) {
            txtName.requestFocus();
            txtName.selectAll();
            JOptionPane.showMessageDialog(this, "The item's name is not empty!", "Notice", JOptionPane.OK_OPTION);
            return false;
        } else if (unit.isEmpty()) {
            txtUnit.requestFocus();
            txtUnit.selectAll();
            JOptionPane.showMessageDialog(this, "The unit is not empty!", "Notice", JOptionPane.OK_OPTION);
            return false;
        } else if (price.isEmpty()) {
            txtPrice.requestFocus();
            txtPrice.selectAll();
            JOptionPane.showMessageDialog(this, "The price is not empty!", "Notice", JOptionPane.OK_OPTION);
            return false;
        } else if (status.isEmpty()) {
            txtStatus.requestFocus();
            txtStatus.selectAll();
            JOptionPane.showMessageDialog(this, "The status is not empty!", "Notice", JOptionPane.OK_OPTION);
            return false;
        } else if (!MyLibrary.checkDoubleNumber(price)) {
            txtPrice.requestFocus();
            txtPrice.selectAll();
            JOptionPane.showMessageDialog(this, "The price is float!", "Notice", JOptionPane.OK_OPTION);
            return false;
        } else if (!MyLibrary.checkIntNumber(status)) {
            txtStatus.requestFocus();
            txtStatus.selectAll();
            JOptionPane.showMessageDialog(this, "The status is integer!", "Notice", JOptionPane.OK_OPTION);
            return false;
        }
        return true;
    }

    public boolean isExistedItemID(String itemID) {
        for (Item i : items) {
            if (i.getItemID().equals(itemID)) {
                return true;
            }
        }
        return false;
    }

    public Item getCurrentItem() {
        String id = txtItemID.getText();
        String name = txtName.getText();
        String unit = txtUnit.getText();
        double price = Double.parseDouble(txtPrice.getText());
        int status = Integer.parseInt(txtStatus.getText());
        String cateID = categories.get(cboCategories.getSelectedIndex()).getCateID();
        boolean returnable = chkReturnable.isSelected();

        return new Item(id, name, unit, status, price, returnable, cateID);
    }

    private void newFilter(String txt, int mode) {
        RowFilter<TableModel, Object> rf = null;
        // If current expression doesn't parse, don't update.
        try {
            rf = RowFilter.regexFilter(txt, mode);
        } catch (java.util.regex.PatternSyntaxException e) {
            return;
        }
        sorter.setRowFilter(rf);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lblBanner = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        txtItemID = new javax.swing.JTextField();
        txtName = new javax.swing.JTextField();
        txtUnit = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        txtStatus = new javax.swing.JTextField();
        txtPrice = new javax.swing.JTextField();
        cboCategories = new javax.swing.JComboBox();
        chkReturnable = new javax.swing.JCheckBox();
        lblSearchTitle = new javax.swing.JLabel();
        lblKeyword = new javax.swing.JLabel();
        txtSearch = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        cboSearchBy = new javax.swing.JComboBox();
        jSeparator1 = new javax.swing.JSeparator();
        jScrollPane1 = new javax.swing.JScrollPane();
        itemTable = new javax.swing.JTable();
        jButton12 = new javax.swing.JButton();

        setBackground(new java.awt.Color(255, 255, 255));
        setMinimumSize(new java.awt.Dimension(700, 300));
        setPreferredSize(new java.awt.Dimension(747, 591));
        setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        lblBanner.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/banner2.jpg"))); // NOI18N
        lblBanner.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        lblBanner.setName("lblBanner"); // NOI18N
        add(lblBanner, new org.netbeans.lib.awtextra.AbsoluteConstraints(-10, 0, 1190, 90));

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));
        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Item Information", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Lucida Sans", 1, 14), new java.awt.Color(0, 0, 255))); // NOI18N
        jPanel1.setName("jPanel1"); // NOI18N
        jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jLabel1.setText("Item ID");
        jLabel1.setName("jLabel1"); // NOI18N
        jPanel1.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(51, 51, -1, 17));

        jLabel2.setText("Name");
        jLabel2.setName("jLabel2"); // NOI18N
        jPanel1.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 80, -1, 20));

        jLabel3.setText("Unit");
        jLabel3.setName("jLabel3"); // NOI18N
        jPanel1.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(68, 113, -1, 17));

        jLabel4.setText("Status");
        jLabel4.setName("jLabel4"); // NOI18N
        jPanel1.add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(250, 50, -1, -1));

        txtItemID.setFocusable(false);
        txtItemID.setName("txtItemID"); // NOI18N
        jPanel1.add(txtItemID, new org.netbeans.lib.awtextra.AbsoluteConstraints(105, 49, 130, -1));

        txtName.setFocusable(false);
        txtName.setName("txtName"); // NOI18N
        jPanel1.add(txtName, new org.netbeans.lib.awtextra.AbsoluteConstraints(105, 80, 210, -1));

        txtUnit.setFocusable(false);
        txtUnit.setName("txtUnit"); // NOI18N
        jPanel1.add(txtUnit, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 110, 120, -1));

        jLabel5.setText("Price");
        jLabel5.setName("jLabel5"); // NOI18N
        jPanel1.add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(340, 80, -1, -1));

        jLabel6.setText("Category");
        jLabel6.setName("jLabel6"); // NOI18N
        jPanel1.add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 110, -1, -1));

        txtStatus.setFocusable(false);
        txtStatus.setName("txtStatus"); // NOI18N
        jPanel1.add(txtStatus, new org.netbeans.lib.awtextra.AbsoluteConstraints(294, 50, 110, -1));

        txtPrice.setFocusable(false);
        txtPrice.setName("txtPrice"); // NOI18N
        jPanel1.add(txtPrice, new org.netbeans.lib.awtextra.AbsoluteConstraints(372, 80, 140, -1));

        cboCategories.setFocusable(false);
        cboCategories.setName("cboCategories"); // NOI18N
        jPanel1.add(cboCategories, new org.netbeans.lib.awtextra.AbsoluteConstraints(292, 110, 220, -1));

        chkReturnable.setBackground(new java.awt.Color(255, 255, 255));
        chkReturnable.setText(" Returnable");
        chkReturnable.setFocusable(false);
        chkReturnable.setName("chkReturnable"); // NOI18N
        chkReturnable.setRolloverEnabled(false);
        chkReturnable.setVerifyInputWhenFocusTarget(false);
        jPanel1.add(chkReturnable, new org.netbeans.lib.awtextra.AbsoluteConstraints(430, 50, -1, -1));

        lblSearchTitle.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N
        lblSearchTitle.setForeground(new java.awt.Color(0, 0, 204));
        lblSearchTitle.setText("Search for item(s)");
        lblSearchTitle.setName("lblSearchTitle"); // NOI18N
        jPanel1.add(lblSearchTitle, new org.netbeans.lib.awtextra.AbsoluteConstraints(670, 20, -1, 25));

        lblKeyword.setText("Keyword:");
        lblKeyword.setName("lblKeyword"); // NOI18N
        jPanel1.add(lblKeyword, new org.netbeans.lib.awtextra.AbsoluteConstraints(620, 80, 60, 20));

        txtSearch.setName("txtSearch"); // NOI18N
        txtSearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtSearchActionPerformed(evt);
            }
        });
        jPanel1.add(txtSearch, new org.netbeans.lib.awtextra.AbsoluteConstraints(680, 80, 186, -1));

        jLabel8.setText("Search by:");
        jLabel8.setName("jLabel8"); // NOI18N
        jPanel1.add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(610, 110, 60, 20));

        cboSearchBy.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Name", "Category" }));
        cboSearchBy.setName("cboSearchBy"); // NOI18N
        jPanel1.add(cboSearchBy, new org.netbeans.lib.awtextra.AbsoluteConstraints(680, 110, 186, -1));

        jSeparator1.setOrientation(javax.swing.SwingConstants.VERTICAL);
        jSeparator1.setName("jSeparator1"); // NOI18N
        jPanel1.add(jSeparator1, new org.netbeans.lib.awtextra.AbsoluteConstraints(560, 20, 1, 133));

        add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 90, 970, 170));

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        itemTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Item ID", "Name", "Category", "Unit", "Price", "Status", "Returnable"
            }
        ));
        itemTable.setAlignmentX(0.0F);
        itemTable.setAlignmentY(0.0F);
        itemTable.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        itemTable.setName("tableItem"); // NOI18N
        itemTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                itemTableMouseReleased(evt);
            }
        });
        jScrollPane1.setViewportView(itemTable);

        add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 270, 1030, 320));

        jButton12.setBackground(new java.awt.Color(255, 255, 255));
        jButton12.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jButton12.setForeground(new java.awt.Color(0, 0, 204));
        jButton12.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/help icon 48.png"))); // NOI18N
        jButton12.setText("   Help   ");
        jButton12.setFocusable(false);
        jButton12.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton12.setName("jButton12"); // NOI18N
        jButton12.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton12.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton12ActionPerformed(evt);
            }
        });
        add(jButton12, new org.netbeans.lib.awtextra.AbsoluteConstraints(550, 610, -1, -1));
    }// </editor-fold>//GEN-END:initComponents

    //reset all data in form
    public void resetForm() {
        txtItemID.setText("");
        txtName.setText("");
        txtPrice.setText("");
        txtStatus.setText("");
        txtUnit.setText("");
        chkReturnable.setSelected(false);
    }
    //back to home
    private void itemTableMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_itemTableMouseReleased
        // TODO add your handling code here:
        try {
            int index=  sorter.convertRowIndexToModel(itemTable.getSelectedRow());
            if (index > -1) {
                item = items.get(index);
                setData(item);
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Error: " + ex.getMessage(), "Notice", JOptionPane.OK_OPTION);
        }
    }//GEN-LAST:event_itemTableMouseReleased

    private void txtSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtSearchActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtSearchActionPerformed

    private void jButton12ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton12ActionPerformed
        // TODO add your handling code here:

        try {
            // TODO add your handling code here:
            InventoryManagement.OpenManual();
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null, "cannot locate manual file in 'manual/ISM_Manual.htm'");
        }
    }//GEN-LAST:event_jButton12ActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox cboCategories;
    private javax.swing.JComboBox cboSearchBy;
    private javax.swing.JCheckBox chkReturnable;
    private javax.swing.JTable itemTable;
    private javax.swing.JButton jButton12;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JLabel lblBanner;
    private javax.swing.JLabel lblKeyword;
    private javax.swing.JLabel lblSearchTitle;
    private javax.swing.JTextField txtItemID;
    private javax.swing.JTextField txtName;
    private javax.swing.JTextField txtPrice;
    private javax.swing.JTextField txtSearch;
    private javax.swing.JTextField txtStatus;
    private javax.swing.JTextField txtUnit;
    // End of variables declaration//GEN-END:variables
}
